
class WSocket{
  constructor(param = {}){
    this.param = param;
    this.socket = null;
    this.taskRemindInterval  = null;
  }
  connection = () => {
    let {socketUrl,timeout=0} = this.param;
    //检测当前浏览器连接socket
    if('WebSocket' in window){
      // console.log(11);
      this.socket = new WebSocket(socketUrl);
    }
    // else if('MozWebSocket' in window){
    //   this.socket = new MozWebSocket(socketUrl);
    // }
    // else{
    //   this.socket = new SockJS(socketUrl);
    // }

    this.socket.onopen = this.onopen;
    this.socket.onmessage = this.onmessage;
    this.socket.onclose = this.onclose;
    this.socket.onerror = this.onerror;
    this.socket.sendMessage = this.sendMessage;
    this.socket.closeSocket = this.closeSocket;
    //检测返回码
    if(timeout){
      return new Promise((resolve,reject) => {
        let time = setTimeout(() => {
          if(this.socket && this.socket.readyState !== 1){
            console.log(this.socket);
            this.socket.close();
            reject('连接超时');
          }
          resolve('连接成功');
          clearTimeout(time);
        },timeout)
      })
    }
    else{
      return new Promise((resolve,reject) => {
        if(true){
          resolve('连接成功');
        }
        else{
          reject('连接超时');
        }
      })
    }
  }
  //连接成功触发
  onopen = () => {
    let {socketOpen,name} = this.param;
    this.isSuccess = false;
    // this.sendMessage(name);
    socketOpen && socketOpen();
  }
  //接受信息
  onmessage = (msg) => {
    let {socketMessage} = this.param;
    socketMessage && socketMessage(msg);
  }
  //关闭连接触发
  onclose = (e) => {
    this.isSuccess = true;
    let {socketClose} = this.param;
    socketClose && socketClose(e);
    if(e.code === '4500'){
      this.socket.close();
    }
    else{
      this.taskRemindInterval = setInterval(()=>{
        if(this.isSuccess){
          this.connection();
        }
        else{
          clearInterval(this.taskRemindInterval);
        }
      },20000);
    }
  }
  //
  onerror = (e) => {
    let {socketError} = this.param;
    this.socket = null;
    socketError && socketError(e);
  }
  //发送信息
  sendMessage = (msg) => {
    if(this.socket){
      this.socket.send(JSON.stringify(msg));
    }
  }
}
export default WSocket;